package com.hyper_yang.javase.reflection_annotation.method;

import org.junit.jupiter.api.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class MethodTest {
    @Test
    public void test1() throws ClassNotFoundException {
        // todo: 获取类的所有方法
        // 1、获取类对象
        Class<?> teacherClass = Class.forName("com.hyper_yang.reflection_annotation.method.Teacher");
        // 2、获取类的方法
        // getMethods() 获取父类+子类的公开方法
//        for (Method method : teacherClass.getMethods()) {
        // getDeclaredMethods() 获取子类独有的所有方法
        for (Method method : teacherClass.getDeclaredMethods()) {
            System.out.println(method);
        }

    }

    @Test
    public void test2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // todo: 获取执行类的公开方法
        // 1、获取类对象
        Class<?> teacherClass = Class.forName("com.hyper_yang.reflection_annotation.method.Teacher");
        // 2、获取方法对象
        Method eat = teacherClass.getMethod("eat", String.class);
        // 3、由于不是静态方法、需要创建类的对象--实例化
        Object o = teacherClass.newInstance();
        // 4、调用方法
        Object invoke = eat.invoke(o, "🍎");
        System.out.println(invoke);
    }

    @Test
    public void test3() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // todo: 获取执行类的非公开方法
        // 1、获取类对象
        Class<?> teacherClass = Class.forName("com.hyper_yang.reflection_annotation.method.Teacher");
        // 2、获取方法对象
        Method run = teacherClass.getDeclaredMethod("run", double.class);
        Object o = teacherClass.newInstance();
        run.setAccessible(true);
        // 调用
        Object invoke = run.invoke(o, 3.3);
        System.out.println(invoke);

    }

    @Test
    public void test4() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 1、获取类对象
        Class<?> teacherClass = Class.forName("com.hyper_yang.reflection_annotation.method.Teacher");
        // 2、获取方法对象
        Method add = teacherClass.getDeclaredMethod("add", int.class, int.class);
        add.setAccessible(true);
        // 调用
        Object invoke = add.invoke(null, 3, 4);
        System.out.println(invoke);
    }
}
